import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import axios from '../until/fetch'

const login = () => import('@/components/login/login')
const home = () => import('@/components/home/home')
const homeEdit = () => import('@/components/home/homeEdit')
const chat = () => import('@/components/chat/chat')
const about = () => import('@/components/about/about')
const infoRelease = () => import('@/components/info/infoRelease')
const preciseSearch = () => import('@/components/info/preciseSearch')
const infoResult = () => import('@/components/info/infoResult')
const PropertyAdmin = () => import('@/components/about/PropertyAdmin')
const myCollection = () => import('@/components/about/myCollection')
const changePSD = () => import('@/components/about/changePSD')
Vue.use(Router)

const router = new Router({
  mode: 'history',
  linkActiveClass: 'curr',
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: login,
      name: 'login'
    },
    {
      path: '/home',
      component: home,
      name: 'home',
      meta: { requireAuth: true } // 路由守卫，可以检测是否登录
    },
    {
      path: '/homeEdit',
      component: homeEdit,
      meta: { requireAuth: true }
    },
    {
      path: '/chat',
      component: chat,
      name: 'chat',
      meta: { requireAuth: true }
    },
    {
      path: '/infoRelease',
      component: infoRelease,
      name: 'infoRelease',
      meta: { requireAuth: true }
    },
    {
      path: '/preciseSearch',
      component: preciseSearch,
      name: 'preciseSearch',
      meta: { requireAuth: true }
    },
    {
      path: '/infoResult',
      component: infoResult,
      name: 'infoResult',
      meta: { requireAuth: true }
    },
    {
      path: '/about',
      component: about,
      name: 'about',
      meta: { requireAuth: true }
    },
    {
      path: '/PropertyAdmin',
      component: PropertyAdmin,
      meta: { requireAuth: true }
    }, {
      path: '/myCollection',
      component: myCollection,
      meta: { requireAuth: true }
    }, {
      path: '/changePSD',
      component: changePSD,
      meta: { requireAuth: true }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    axios.get('/api/Login/IsLogin')
      .then((response) => {
        const res = response.data
        if (res.code == 0) {
          next({ path: '/' })
        } else {
          store.commit('saveUser', res.object)
          next()
        }
      })
      .catch((err) => {
        console.log(err)
      })
    next()
  } else {
    next()
  }
})

export default router
